<template>
  <van-list
    v-model="loading"
    :finished="finished"
    finished-text="没有更多了"
    :immediate-check="false"
    @load="onLoad"
  >
    <commentItem
      v-for="(item, index) in list"
      :key="index"
      :comment="item"
      @reply-click="$emit('reply-click', $event)"
    />
  </van-list>
</template>

<script>
import { getComment } from "@/api/comment.js";
import commentItem from "@/views/article/components/comment-item.vue";
export default {
  props: {
    artId: {
      type: [Number, String, Object],
      required: true,
    },
    list: {
      type: Array,
      default: () => [],
    },
    type: {
      type: String,
      validator(value) {
        return ["a", "c"].includes(value);
      },
      default: "a",
    },
  },
  components: {
    commentItem,
  },
  created() {
    this.loading = true;
    this.onLoad();
  },
  data() {
    return {
      loading: false,
      finished: false,
      offset: null, //获取评论数据的偏移量，值为评论id，表示从此id的数据向后取，不传表示从第一页开始读取数据
      limit: 10, //获取的评论数据个数，不传表示采用后端服务设定的默认每页数据量
      total_count: 0,
    };
  },
  methods: {
    async onLoad() {
      // console.log(this.artId,1111)
      try {
        // console.log(this.type,'这是artId')
        // 1.获取评论列表的数据
        const { data } = await getComment({
          type: this.type,
          source: this.artId.toString(),
          offset: this.offset,
          limit: this.limit,
        });
        // console.log(data);
        // 2.将数据添加到列表中
        const results = data.data.results;
        this.list.push(...results);
        // 因为后台没有一个is_liking为true,所以手动更改一下,然后看一下效果
        this.list[4].is_liking = true;
        // console.log(this.list)
        this.$emit("onloadSuccess", data.data);
        // 3.将加载的loading设置为false
        this.loading = false;
        // 4.判断后续请求的数据中是否还有数据
        if (results.length) {
          this.offset = data.data.last_id;
        } else {
          this.finished = true;
        }
      } catch (err) {
        this.$toast("数据加载失败");
      }
    },
  },
};
</script>

<style>
</style>